/**
 * 
 */
package ae.pcfc.cldos.online.web.controller.admin.workflow.backoffice.review;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.UnhandledException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import ae.pcfc.cldos.online.common.ConstantsCommon.Steps;
import ae.pcfc.cldos.online.common.UltimusConstants.AdminDecision;
import ae.pcfc.cldos.online.common.delegate.EmploymentVisaDelegate;
import ae.pcfc.cldos.online.common.delegate.GeneralAdminDelegate;
import ae.pcfc.cldos.online.common.exception.NoPaymentForBGZeroException;
import ae.pcfc.cldos.online.common.exception.PaymentException;
import ae.pcfc.cldos.online.common.vo.BackOfficeAdminVO;
import ae.pcfc.cldos.online.common.vo.CommentsVO;
import ae.pcfc.cldos.online.common.vo.EmployeVisaVO;
import ae.pcfc.cldos.online.common.vo.FileVO;
import ae.pcfc.cldos.online.common.vo.UserVO;
import ae.pcfc.cldos.online.common.vo.employee.details.AddressDetailsVO;
import ae.pcfc.cldos.online.common.vo.employee.details.EmployeeDetailsVO;
import ae.pcfc.cldos.online.common.vo.employee.details.PassportDetailsVO;
import ae.pcfc.cldos.online.common.vo.employee.details.PersonalDetailsVO;
import ae.pcfc.cldos.online.web.Constants;
import ae.pcfc.cldos.online.web.PageType;
import ae.pcfc.cldos.online.web.ViewPath;
import ae.pcfc.cldos.online.web.ViewUtils;
import ae.pcfc.cldos.online.web.controller.base.BaseNewVisaController;
import ae.pcfc.cldos.online.web.model.BackOfficeAdminReview;
import ae.pcfc.cldos.online.web.model.EmploymentVisaLicenseInfo;

/**
 * @author Abed
 *
 */
@Controller
@RequestMapping(value = ViewPath.__BACKOFFICE_ADMIN_EMPLOYMENT_VISA_REVIEW)
public class BackOfficeAdminEmploymentVisaReviewController extends BaseNewVisaController {
	
	@Autowired
	@Qualifier("employmentVisaDelegate")
	private EmploymentVisaDelegate employmentVisaDelegate;
	
	@Autowired
	@Qualifier("generalAdminDelegate")
	private GeneralAdminDelegate generalAdminDelegate;
	
	@ModelAttribute(Constants.__BACKOFFICE_COMPANY_EMPLOYMENT_VISA_REVIEWER_LICENSE_INFO_REQUEST_MODEL_KEY)
	public EmploymentVisaLicenseInfo populateRegisterEmploymentVisaReviewerInfoModel(@RequestParam String appId,
			HttpServletRequest request, ModelMap model,
			@ModelAttribute(value = "backOfficeAdminReview") BackOfficeAdminReview adminReview) throws Exception {
		
		EmploymentVisaLicenseInfo employmentVisaInfo = new EmploymentVisaLicenseInfo();
		if(appId != null){
			//::TODO FIXME GENERAL ADMIN VO!!!!
			UserVO userVO =  getUserVO();
			userVO.setGeneralAdmin(true);
			EmployeVisaVO employeVisaVO = employmentVisaDelegate.getEmployeeVisaDetailByAppId(appId,userVO, Steps.DOCUMENT_AND_DATA_VALIDATION);
			
			if(employeVisaVO != null){
				adminReview.setClientReferenceNo(employeVisaVO.getClientReferenceNo());
				adminReview.setInitiatedBy(employeVisaVO.getInitiatedBy());
				
				AddressDetailsVO addressDetailsVO = employeVisaVO.getAddressDetailsVO();
				mapper.map(addressDetailsVO, employmentVisaInfo);
				CommentsVO commentsVO = employeVisaVO.getCommentsVO();
				mapper.map(commentsVO, employmentVisaInfo);
				EmployeeDetailsVO employeeDetailsVO = employeVisaVO.getEmployeeDetailsVO();
				mapper.map(employeeDetailsVO, employmentVisaInfo);
				PassportDetailsVO passportDetailsVO = employeVisaVO.getPassportDetailsVO();
				mapper.map(passportDetailsVO, employmentVisaInfo);
				PersonalDetailsVO personalDetailsVO = employeVisaVO.getPersonalDetailsVO();
				mapper.map(personalDetailsVO, employmentVisaInfo);

				List<FileVO> fileVOList = employeVisaVO.getFileVOList();
				System.out.println(fileVOList);
				model.put("files", fileVOList);
				model.put("comments", employeVisaVO.getApplicationCommentVOs());
				model.put("warnings", employeVisaVO.getWarningCommentsVOs());
			}else{
				throw new UnhandledException("Not Data found for App Id: "+ appId, null);
			}
		}
		return employmentVisaInfo;
	}
	
	
	@RequestMapping(value = "/form.htm", method = RequestMethod.GET)
	public void form(@RequestParam(value = "appId", required = true) String appid,
			@RequestParam(value = "UserName", required = true) String userName,
			@RequestParam(value = "ProcessName", required = false) String processName,
			@RequestParam(value = "TaskID", required = true) String taskID,
			@RequestParam(value = "Incident", required = true) String incident,
			@RequestParam(value = "StepName", required = true) String stepName,
			@ModelAttribute(value = "backOfficeAdminReview") BackOfficeAdminReview adminReview){

		adminReview.setStrApplicationId(appid);
		adminReview.setStrUserName(userName);
		adminReview.setStrTaskId(taskID);
		adminReview.setStrIncidentNo(incident);
		adminReview.setStrStepName(stepName);
		adminReview.setProcessName(processName);
	}
	
	
	@RequestMapping(method = RequestMethod.POST, value = "/form.htm")
	public ModelAndView form(
			HttpServletRequest request,
			SessionStatus status,
			@ModelAttribute(value = Constants.__BACKOFFICE_COMPANY_EMPLOYMENT_VISA_REVIEWER_LICENSE_INFO_REQUEST_MODEL_KEY) EmploymentVisaLicenseInfo employmentVisaLicenseInfo,
			BindingResult errors,
			@ModelAttribute(value = "backOfficeAdminReview") BackOfficeAdminReview adminReview
			) throws Exception {
		
		boolean isSubmitApproval = WebUtils.hasSubmitParameter(request, "MainUserApprove");
		boolean isSubmitReject = WebUtils.hasSubmitParameter(request, "MainUserReject");
		boolean isSubmitCancel = WebUtils.hasSubmitParameter(request, "MainUserCancel");
		
		BackOfficeAdminVO backOfficeAdminVO = new BackOfficeAdminVO();
		mapper.map(adminReview, backOfficeAdminVO);
		
		String adminComments = employmentVisaLicenseInfo.getAdminComments();
		
		if(isSubmitApproval){
			System.out.println("BackOffice Approved...");
			backOfficeAdminVO.setStrActionType(AdminDecision.APPROVED.getAdminDecision());
		}else if(isSubmitReject){
			if(adminComments==null || adminComments.isEmpty()){
				errors.reject("admin.comment.required");
			}
			System.out.println("BackOffice Rejected...");
			backOfficeAdminVO.setStrActionType(AdminDecision.REJECTED.getAdminDecision());
		} else if(isSubmitCancel){
			System.out.println("BackOffice Canceled...");
			backOfficeAdminVO.setStrActionType(AdminDecision.CANCELLED.getAdminDecision());
		}
		
		backOfficeAdminVO.setStrComments(adminComments);
		
		String clientRefNo = null;
		
		if(!errors.hasErrors()){
			try{
				clientRefNo = generalAdminDelegate.reviewByBackOffice(backOfficeAdminVO);
			} catch (PaymentException e) {
				errors.reject("", e.getCause().getMessage());
			} catch (NoPaymentForBGZeroException e) {
				errors.reject("bg.insufficient.no.payment");
			} 
		}
		ModelAndView mav = null;
		
		if(!errors.hasErrors()){
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put(Constants.__REFRENCE_NO, clientRefNo);
			
			paramMap.put("Incident", adminReview.getStrIncidentNo());
			paramMap.put("StepName", adminReview.getStrStepName());
			paramMap.put("InitiatedBy", adminReview.getInitiatedBy());
			
			status.setComplete();
			mav =new ModelAndView(ViewUtils.getRedirect(ViewPath.__BACKOFFICE_CONFIRMATION, PageType.SHOW, paramMap)); 
		} else {
			mav = ViewUtils.DEFAULT_VIEW;
		}

		return mav;
	}

}
